package ar.sensor;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import ar.camera.glsurfaceview.base.BaseGLSurfaceView;
import ar.camera.glsurfaceview.extend.MiniMapSurfaceView;
import ar.camera.pojo.GLPoint;
import ar.camera.renderer.extend.LocationIconRenderer;
import ar.globals.Globals;
import ar.utils.GLIconUtils;

public class SensorListener implements SensorEventListener {

	private BaseGLSurfaceView mPlaneView;
	private BaseGLSurfaceView mLocationIconView;
	private BaseGLSurfaceView mCompassView;
	private long lastUpdate;

	public SensorListener() {
		super();
	}

	public SensorListener(BaseGLSurfaceView mVirtualPlane,
			BaseGLSurfaceView mVirtualTexture, BaseGLSurfaceView mMiniCompass) {
		super();
		this.mPlaneView = mVirtualPlane;
		this.mLocationIconView = mVirtualTexture;
		this.mCompassView = mMiniCompass;

		lastUpdate = System.currentTimeMillis();
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {

		if (event.accuracy != SensorManager.SENSOR_STATUS_ACCURACY_HIGH)
			return;

		if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
			long actualTime = System.currentTimeMillis();
			if (actualTime - lastUpdate < 15 || event.values[2] < 45) {
				return;
			}
			lastUpdate = actualTime;

			if (event.values[2] < 45)
				return;

			float x = event.values[0];
			Log.v("x", String.valueOf(x));

			GLPoint cam = new GLPoint(0, 0, -1);
			GLPoint center = new GLPoint(0, 0, 0);
			float azm = (float) ((90 - x) * Math.PI / 180);
			cam = GLIconUtils.rotateY(cam, center, azm);

			if (mLocationIconView != null
					&& mLocationIconView.getmRenderer() != null) {
				if (((LocationIconRenderer) mLocationIconView.getmRenderer())
						.isUpdateSensor()) {

					mLocationIconView.getmRenderer().updateVertices(90 - x,
							null, null);
					mLocationIconView.getmRenderer().setCam(cam);
					mPlaneView.getmRenderer().setCam(cam);
					((MiniMapSurfaceView) mCompassView)
							.updateCompassVertices(x + 90,
									new GLPoint(0, 0, 0), new GLPoint(0, 0, -1));
				}
			}
			Globals.routeAzimut = event.values[0];
			Globals.isNeedUpdatedRouteCompass = true;
		}
	}
}
